<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>smap-query</title>
    <link href="/media/bootstrap3/css/bootstrap.min.css" rel="stylesheet" media="screen">

    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.0.1/d3.v3.min.js"></script>
    <script src="/media/bootstrap3/js/bootstrap.min.js"></script>
    <script src="/media/smap/js/smaputil.js"></script>

    <style>
      body {
        overflow: hidden;
        font-family: "Lucida Console", Monaco, monospace;
      }
      #console, #submit-button{
        font-size: 18px;
        border-radius: 0px;
        height: 50px;
      }
      #output-raw-pre {
        border-radius: 0px;
        font-family: "Lucida Console", Monaco, monospace;
        overflow: auto;
        font-size: 14px;
      }
      #output-vis {        
        overflow: auto;
      }
      .streamchart {
        font: 10px sans-serif;
        margin-bottom: 12px;
        margin-top: 12px;
      }
      .axis path, .axis line {
        fill: none;
        stroke: #000;
        shape-rendering: crispEdges;
      }
      .line {
        fill: none;
        stroke: steelblue;
        stroke-width: 1.5px;
      }
      .loading {
        display:    none;
        position:   fixed;
        z-index:    1000;
        top:        0;
        left:       0;
        height:     100%;
        width:      100%;
        background: rgba( 230, 230, 230, 0.4 ) 
                    url('/media/smap/img/ajax-loader.gif') 
                    50% 50% 
                    no-repeat;
      }
    </style>

  </head>

  <body>

    <div class="row" id="input">
      <div class="col-12">
        <div class="input-group">
          <input type="text" class="form-control" id="console">
          <span class="input-group-btn">
            <button class="btn btn-default" type="button" id="submit-button">&#9166;</button>
          </span>
        </div>
      </div>
    </div>

    <div class="row" id="output">
      <div class="col-6" id="output-raw">
        <pre id="output-raw-pre" class=".pre-scrollable"></pre>
      </div>
      <div class="col-6" id="output-vis"></div>
    </div>

    <div class="loading"></div>
    <script>
      var url = "/backend/api/query";
      var history = []
      var ihist = 0;
      
      $("#console").keydown(function(event){
        if(event.keyCode == 13){ // enter
          $("#submit-button").click()
        } else if(event.keyCode == 38){ // up
          var N = history.length
          if (ihist < N) {
            $("#console").val(history[ihist]) 
            ihist += 1;
          }
        } else if(event.keyCode == 40){ // down
          var N = history.length
          if (ihist > 0) {
            ihist -= 1; 
            $("#console").val(history[ihist]) 
          } else if (ihist == 0) {
            $("#console").val("")
          }
        }
      });

      $("#submit-button").click(function(){
        var query = $("#console").val()
        $(".loading").show()
        archiverQuery(query, url, handleResult, handleFailure)
        history.unshift(query) 
        ihist = 0
        $("#output-vis").empty()
        $("#output-raw-pre").empty()
        $('#console').val("")
      });
      
      function renderMetadata(res){
        for (var i=0; i < res.length; i++){
          var uuid = res[i].uuid
          var uom = res[i].Properties.UnitofMeasure
          var path = res[i].Path
          var label = path + " [" + uom + "]"
          $("#"+uuid).text(label)
        }
      }

      function handleResult(res){
        var res_str = JSON.stringify(res, null, 4);
        $("#output-raw-pre").html(res_str)
        for (var i = 0; i < res.length; i++){
          r = res[i] 
          if (r.hasOwnProperty("Readings")){
            if (typeof r.Readings != "string"){
              renderStreamChart(r)
            }
          }
        }    
        var uuids = _.pluck(res, 'uuid')
        var fields = ['uuid', 'Path', 'Properties/UnitofMeasure']
        smaputil.getMetadata(uuids, fields, renderMetadata)
        $('.loading').hide()
      }

      function handleFailure(res, textStatus, errorThrown){
        if (res.status==200){ 
          try {
            var chunks = res.responseText.split("\n")
            chunks.pop()
            var json = []
            var memo_uuids = []
            _.each(chunks, function(chunk){
              var chunk_json = JSON.parse(chunk)
              _.each(chunk_json, function(o){
                var uuid = o.uuid
                var i = memo_uuids.indexOf(uuid)
                if (i==-1){
                  memo_uuids.push(uuid)
                  json.push(o)
                } else {
                  var r = o.Readings
                  json[i].Readings = json[i].Readings.concat(r)
                }
              });
            });
            handleResult(json)
          }
          catch(err) {
            console.log(err)
            $("#output-raw-pre").html("JSON error")
          }
        } else { 
          console.log([textStatus, errorThrown])
          $("#output-raw-pre").html("Query invalid or timed out")
        }
        $('.loading').hide()
      }

      function convertJSON(data){
        var json = []
        for (var j in data){
          var el = data[j];
          if (el[1] != null) {
            json.push({"timestamp": el[0], "reading": el[1]});
          }
        }
        return json;
      }

      function renderStreamChart(data){
        var json = convertJSON(data.Readings)  

        if (json.length < 2) return

        var margin = {top: 20, right: 20, bottom: 20, left: 50},
            width = $(window).width() / 2 - margin.left - margin.right - 20,
            height = 300 - margin.top - margin.bottom;
            
        var x = d3.time.scale()
            .range([0, width]);

        var y = d3.scale.linear()
            .range([height, 0]);

        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom");

        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left");

        var line = d3.svg.line()
            .x(function(d) { return x(d.timestamp); })
            .y(function(d) { return y(d.reading); });
            
        x.domain(d3.extent(json, function(d) { return d.timestamp; }));
        y.domain(d3.extent(json, function(d) { return d.reading; }));

        var svg = d3.select("#output-vis").append("svg")
            .attr("class", "streamchart")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
          .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
         
        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);
           
        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
           .append("text")
             .attr("class", "label-text")
             .attr("id", data.uuid)
             .attr("y", -7)
             .attr("x", 10)
             .style("font-size", "12")
             .style("text-anchor", "start")
             
        svg.append("path")
            .datum(json)
            .attr("class","line")
            .attr("d", line);          
      }
     
      function archiverQuery(query, url, success_callback, fail_callback){
        $.ajax({
          url: url,
          type: "post",
          data: query,
          timeout: 120000,
          dataType: 'text json',
          success: success_callback,
          error: fail_callback
        });
      }

      $(document).ready(function(){
        var h = $(window).height() - $('#console').outerHeight() - 4
        $("#output-raw-pre").height(h)
        $("#output-vis").height(h)
        $("#console").focus()
      });

    </script>
  </body>
</html>

